package com.jagochan.module.rbac.common.exception;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.jagochan.common.result.ResultUtils;
import com.jagochan.common.result.ResultVo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 自定义业务异常拦截
     * BusinessException
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public ResultVo bussinessexception(BusinessException e) {
        System.out.println(("\033[31m" + e.getMessage() + "\033[0m"));
        return ResultUtils.error(e.getMessage(), e.getCode(), e.getMessage());
    }


    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultVo handlerException(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        int code = 500;
        String str;
        // 打印堆栈，以供调试
        System.out.println("全局异常---------------");
        e.printStackTrace();

        //无角色的异常
        if (e instanceof NotRoleException) {        // 如果是角色异常
            NotRoleException ee = (NotRoleException) e;
            str = ("无此角色：" + ee.getRole());
        }
        //无权限访问的异常
        else if (e instanceof NotPermissionException) {    // 如果是权限异常
//            NotPermissionException ee = (NotPermissionException) e;
            str = "无权限操作该功能!";
        } else {    // 普通异常, 输出：500 + 异常信息
            str = (e.getMessage());
        }

        // 返回给前端
        return ResultUtils.error(str, code,
                e.getMessage());
    }
}